package sagroup.pdlime;

import lime2.LimeTemplate;
import lime2.Reaction;
import lime2.ReactionListener;


public class VersionedReaction {
	/**
	 * The reaction is fired once and then it is removed automatically from the
	 * reactive program.
	 */
	public static final byte ONCE = 1;

	/**
	 * The reaction is fired, and will never fire again for that given tuple,
	 * but remains registered. So, if multiple tuples enable the reaction, the
	 * reaction is fired for each of them.
	 */
	public static final byte ONCEPERTUPLE = 2;
	public static final byte ONCEPERTUPLEID = 3; //Version ID?

	// is it a once or once-per-tuple reaction ?
	// private byte mode;
	private Reaction reaction;

	/**
	 * @modify limeTemplate
	 * @param mode
	 * @param limeTemplate
	 * @param listener
	 */
	public VersionedReaction(final byte mode, final TVRLimeTemplate vlt,
			final ReactionListener listener) {
		final byte reactionMode;

		// parameter checking
		if (((mode != ONCE) && (mode != ONCEPERTUPLE) && (mode != ONCEPERTUPLEID))
				|| vlt == null || listener == null)
			throw new IllegalArgumentException("invalid/null value");

		else {
			LimeTemplate templateWithVersion = vlt.toLimeTemplate();

			switch (mode) {
			case ONCE:
				reactionMode = Reaction.ONCE;
				reaction = new Reaction(reactionMode, templateWithVersion,
						listener);
				break;
			case ONCEPERTUPLE:
				reactionMode = Reaction.ONCEPERTUPLE;
				reaction = new Reaction(reactionMode, templateWithVersion,
						listener);
				break;
			case ONCEPERTUPLEID:
				reactionMode = Reaction.ONCEPERTUPLE;
				final OncePerVIDListener opiListener = new OncePerVIDListener(
						listener);
				reaction = new Reaction(reactionMode, templateWithVersion,
						opiListener);
				break;
			default:
				break;
			}
		}
	}

	public static Reaction[] getReactions(VersionedReaction[] versionedReactions) {
		Reaction toReturn[] = new Reaction[versionedReactions.length];
		for (int i = 0; i < versionedReactions.length; i++) {
			toReturn[i] = versionedReactions[i].reaction;
		}
		return toReturn;
	}

}
